<?php


namespace app\agent\controller;

use app\admin\library\Auth;
use app\admin\model\agent\Bill;
use app\admin\model\Preproduct;
use app\common\controller\Agent;
use app\admin\model\orders\Shopping as ShoppintCar;
use app\admin\model\Githouse;
use app\common\library\Upload;
use app\common\model\order\Order;
use app\common\model\order\Orderitem;
use app\common\model\order\Orderlog;
use app\common\model\Warehouse;
use workflow\workflow;
use app\admin\model\Admin as WorkAdmin;

use think\Db;

class Shopping extends Agent
{
     protected $noNeedRight = '*';
    public function _initialize()
    {
        parent::_initialize();
        $this->model = new Preproduct();
        $this->modelWarehouse = new Warehouse();
        $this->view->assign("provinceOrderList", $this->modelWarehouse->getProvinceOrderList());
        $this->view->assign("cityOrderList", $this->modelWarehouse->getcityOrderList());
        $this->view->assign("areaOrderList", $this->modelWarehouse->getAreaOrderList());
        $this->view->assign('shoppingCar',ShoppintCar::shoppingCart($this->auth->id,1));
    }

    public function index()
    {
        $list = ShoppintCar::alias('a')
            ->field('a.id as sid,a.*,b.*')
            ->where(['a.agentid'=>$this->auth->id])
            ->where(['a.sorter'=>1])
            ->join('hdyj_preproduct b','a.fid = b.id')
            ->select();
        $this->view->assign('list',$list);
        //print_r($this->auth->group_id);die;
        return $this->view->fetch();
    }

    /**
     * 生产订单
     */
    public function productionOrdes()
    {
        if($this->request->isPost())
        {
            $row['remark'] = $this->request->request('remark','');//备注
            $row['githouse_id'] =$this->request->request('githouse_id',0);//收货地址
            $row['receivingWay'] = $this->request->request('receivingWay','');
            $row['freightFor'] = $this->request->request('freightFor','');
            $row['forArrivalGoodsTime'] = $this->request->request('forArrivalGoodsTime','');
            $row['nb'] = getOrderNo('DL-S');//生产订单号
            $row['dep_id'] = $this->auth->id;//仓库id
            $row['userid'] = $this->auth->userid;//代理商ID
            $row['sorter'] = 1;//代理商
            $row['status'] = 1;
            $row['pay'] = 1;
            $row['nameAgent'] = $this->auth->agent_name;
            $row['nameShipper'] = '北京宏达一甲';
            $row['shipperTelephone'] = '010-88878286';
            $row['shipperAddress'] = '北京市海淀区蓝靛厂东路2号金源商务中心B座3F';
            $warehouse = Warehouse::where(['agent_id'=>$this->auth->id,'status'=>1,'sorter'=>1])->find();
            $row['consigneeAddress'] =  $warehouse['province_text'].$warehouse['city_text'].$warehouse['area_text'].$warehouse['address'];
            $row['consignee'] =  $warehouse['name'];
            $row['consigneeTelephone'] =  $warehouse['tel'];
            Db::startTrans();
            try{
                //获取购物车商品
                $orderId = Order::create($row)->getLastInsID();
        
                //生产订单
                if(!$shoppingList = ShoppintCar::where(['agentid'=>$this->auth->id,'sorter'=>1])->column('fid as preproduct_id,number as num,remark'))
                {
                    // 回滚事务
                    Db::rollback();
                    $this->error('购物车没有商品！');
                }
                $orderItem = new Orderitem();
                $orderItemArray = [];
                $total = 0;
                if($shoppingList)
                {
                      
                    foreach ($shoppingList as $preproduct_id=>$value)
                    {
                        $value['order_id'] = $orderId;
                        $value['unit_price'] = $this->Price($value['preproduct_id']);
                        $orderItemArray[] = $value;
                        $total += ($value['unit_price'] * $value['num']);
                    }
                }
            
                $orderRow = Order::get($orderId);
                $orderRow->order_price = $total;//计算订单总价格
                $orderRow->save();
                //生产订单详情
                $orderItem->saveAll($orderItemArray,false);

                //提交订货单日志
                Orderlog::create([
                    'order_id'=>$orderId,
                    'userid'=>$this->auth->userid,
                    'dep_id'=>$this->auth->id,
                    'dep_name'=>$this->auth->agent_name,
                    'username'=>$this->auth->username,
                    'content'=>'已提交订货单，等待订货单审核',
                    'action'=>'审批发起',
                    'type'=>1,
                ]);
                //清空购物车
                ShoppintCar::destroy($this->request->request('sid/a'));

                // 提交事务
                Db::commit();
          
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                //提交订单失败   企业微信通知
                $this->error('提交订单失败！');
            }
            if($row = Order::get($orderId)) {
              check_public($orderId,2,$this->auth);
              check_public($orderId,6,$this->auth);
              $this->redirect('/agent/agent/order');
            }
            return $this->view->fetch();
        }
    }

    public function Price($preproduct_id)
    {
        $row = Preproduct::get($preproduct_id);
        return $row['price'];
    }

    /**
     * 确认订单
     * @param $id
     * @return string
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function checkOrder($id)
    {
        //订单详情
        $order = Order::get($id);
       if(!$order || $order->status!= '-1') $this->error('订单不存在或在审核中');
        if($this->request->isPost()) {
            $order->status = 1;
            $order->step = 1;
            if($order->save()){
                check_public($id,2,$this->auth);
                check_public($id,6,$this->auth);
            }
            return $this->redirect('/agent/agent/order');
        }
        $log = Orderlog::where(['dep_id'=>$order['dep_id'],'order_id'=>$id])->select();
        foreach ($log as $key => &$value) {
            $value->avatar = TableField('Admin','avatar',$value['userid'],'userid');
        }

        $order['log'] = $log;
        unset($value);
     
        $agent = Githouse::get(array('id'=>$order['dep_id']));
        $userinfo = WorkAdmin::get(array('userid'=>$order['userid']));
        $orderItem = Orderitem::alias('a')
            ->field('a.*,a.remark as remarks,b.type,b.cname,b.b_n')
            ->where('a.order_id',$id)
            ->join('hdyj_preproduct b','a.preproduct_id = b.id')
            ->select();
        $agent['warehouse'] = Warehouse::where(['agent_id'=>$agent['dep'],'status'=>1,'sorter'=>1])->find();
        $this->view->assign('order',$order);
        $this->view->assign('agent',$agent);
        $this->view->assign('userinfo',$userinfo);
        $this->view->assign('orderItem',$orderItem);
        return $this->view->fetch();
    }

    /**
     * 确认订单 付款
     * @throws \think\exception\DbException
     */
    public function makeSureOrder()
    {

        Db::startTrans();
        try{
            $newFlow = new workflow();
            $order_id = $this->request->request('order_id','0');//生成订单id
            if($row = Order::get($order_id)) {
                //wf_id  流程ID 表flow 2   wf_fid  当前order操作表id
                $data = ['wf_id'=>1,'wf_fid'=>$order_id,'wf_type'=>'order','new_type'=>0,'check_con'=>'订单生成'];
                //是否有审批流程 如果有就不发送消息了
                $newFlow->startworkflow($data,$this->auth->id,2);
                if(!$this->SendWork($order_id))
                {
                    Db::rollback();
                    $this->redirect('/agent/index');
                }
                // 提交事务
                Db::commit();
            }
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $this->redirect('/agent/index');
        }

        $this->redirect('/agent/agent/order');
    }

    /**
     * 生成订单
     * @param $ids  购物车ID
     * @return string
     * @throws \think\Exception
     */
    public function settlement($ids)
    {

        $list = ShoppintCar::alias('a')
            ->field('a.id as sid,a.*,b.*')
            ->where(['a.agentid'=>$this->auth->id])
            ->where(['a.sorter'=>1])
            ->where('a.id','in',$ids)
            ->join('hdyj_preproduct b','a.fid = b.id')
            ->select();
        $total = 0;
        foreach ($list as $key=>&$value){
            $total += $value['number'] * $value['price'];
        }
        $this->view->assign('defaultAddress',Warehouse::get(['agent_id'=>$this->auth->id,'sorter'=>1,'status'=>1]));
        $this->view->assign('list',$list);
        $this->view->assign('total',$total);
        $this->view->assign('WarehouseList',Warehouse::where(['agent_id'=>$this->auth->id,'sorter'=>1])->select());

        return $this->view->fetch();
    }

    /**
     * 查询商品
     * @param $id
     * @throws \think\exception\DbException
     */
    public function goodsInfo($id)
    {
        $row = $this->model->get($id);
        if($row){
            $row['image'] = imgno($row['image']);
            $this->success('请求成功！','',$row);
        }
        $this->error('请求失败！');
    }

    /**
     * 添加到购物车
     */
    public function addToCart()
    {
        if(!$number = (int) $this->request->request('number'))
        {
            $this->error('缺少数量！');
        }
        if(!$fid = $this->request->request('fid'))
        {
            $this->error('缺少商品id！');
        }
        if($number < 1)
        {
            $this->error('数量不能低于1');
        }

        $shoppingcar = ShoppintCar::shoppingCart($this->auth->id,1);
        if ($shoppin = ShoppintCar::get(['agentid'=>$this->auth->id,'fid'=>$fid,'sorter'=>1]))
        {
            $shoppin->number += $number;
            $shoppin->save();
            $this->success('添加到购物车！','',$shoppingcar);
        }

        //sorter=2 代理商下单
        if(!$res = ShoppintCar::create(['number'=>$number,'fid'=>$fid,'agentid'=>$this->auth->id,'sorter'=>1]))
        {
            $this->error('添加购物车失败！');
        }
       
        $shoppingcar = ShoppintCar::shoppingCart($this->auth->id,1);
        $this->success('添加到购物车！','',$shoppingcar);
    }


    /**
     * 购物车数量修改
     * @throws \think\exception\DbException
     */
    public function upCart()
    {
        if(!$fid = (int) $this->request->request('fid'))
        {
            $this->error('参数错误购物车ID！');
        }
        if(!$number = (int) $this->request->request('number'))
        {
            $this->error('数量有误！');
        }
        if(!$row = ShoppintCar::get($fid))
        {
            $this->error('购物车商品不存在！');
        }
        $row->number = $number;
        if(!$row->save())
        {
            $this->error('数量有误！');
        }
        $this->success('操作成功！');

    }

    /**
     * 计算下单金额
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function checkGoods()
    {
        if(!$ids = $this->request->request('ids'))
        {
            $this->error('参数有误！','','0');
        }
        $array = ShoppintCar::alias('a')
            ->field('a.id as sid,a.*,b.*')
            ->where(['a.agentid'=>$this->auth->id])
            ->where(['a.sorter'=>1])
            ->where('a.id','in',$ids)
            ->join('hdyj_preproduct b','a.fid = b.id')
            ->select();
        $list = 0;
        foreach ($array as $key=>$value){
            $list += $value['number'] * $value['price'];
        }
        $this->success('计算金额','',number_format($list,2));
    }

    /**
     * 删除购物车商品
     */
    public function delGoods()
    {
        if(!$ids = $this->request->request('ids','', 'trim'))
        {
            $this->error('参数有误！','','0');
        }
        $arr = explode(',',$ids);
        array_pop($arr);
        if(ShoppintCar::destroy($arr))
        {
            $this->success('删除成功！');
        }
        $this->error('删除失败！');
    }

    /**
     * 发送审核
     *
     */
    protected function SendWork($orderID=null)
    {
        $newFlow = new workflow();
        $array = [
            'touser'=>$this->auth->docking,
            'toparty'=>'',
            'totag'=>'',
            'description'=>$this->auth->agent_name.'下单完成，待确认',
            'urlInfo'=>"http://{$_SERVER['SERVER_NAME']}/index/agent/details/orderID/{$orderID}/userid/{$this->auth->docking}",
            'title'=>'订单审核',
        ];
        return $newFlow->send_work('textcard',$array);
    }

}